<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="3" :xs="24">
        <el-input v-model="lineName" placeholder="请输入产线名称" clearable size="small" prefix-icon="el-icon-search"
                  style="margin-bottom: 20px" />
        <el-tree ref="tree"  :data="lineTreeLists" :props="defaultProps"  :default-checked-keys="checkDefaultLine"
                 :default-expand-all="true" node-key="id" highlight-current @node-click="lineClick" />
      </el-col>
      <el-col :span="21" :xs="24">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="焊缝编号" prop="weldNo">
        <el-input
          v-model="queryParams.weldNo"
          placeholder="请输入焊缝编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="焊缝姿态" prop="weldAttitude">
        <el-select v-model="queryParams.weldAttitude" placeholder="请选择焊缝姿态" clearable>
          <el-option
            v-for="param in parameterLists"
            :key="param.value"
            :label="param.label"
            :value="param.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品类型" prop="productTypeId">
        <el-select v-model="queryParams.productTypeId" placeholder="请选择产品类型" clearable>
          <el-option
            v-for="param in productLists"
            :key="param.value"
            :label="param.label"
            :value="param.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="焊缝长度" prop="weldLength">-->
<!--        <el-input-->
<!--          v-model="queryParams.weldLength"-->
<!--          placeholder="请输入焊缝长度"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['zndd:action:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['zndd:action:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['zndd:action:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['zndd:action:export']"
        >导出</el-button>
      </el-col>

        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-s-claim"
            size="mini"
            @click="openWalkthrough"
          >焊缝预排</el-button>

      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="actionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" v-if="showIdColumn"  />
      <el-table-column label="序号" type="index" :index="indexMethod"></el-table-column>
<!--      <el-table-column label="部门ID" align="center" prop="deptId" />-->
      <el-table-column label="焊缝编号" align="center" prop="weldNo" />
      <el-table-column label="二级产线" align="center" prop="twoLineId" :formatter="twoLineFormatter" />
      <el-table-column label="三级产线" align="center" prop="threeLineId" :formatter="threeLineFormatter" />
      <el-table-column label="产品类型" align="center" prop="productTypeId" :formatter="productFormatter" />
      <el-table-column label="作业类型" align="center" prop="jobType"  :formatter="jobTypeFormatter" />
      <el-table-column label="焊缝区域X" align="center" prop="weldZoneX" />
      <el-table-column label="焊缝区域Y" align="center" prop="weldZoneY" />
      <el-table-column label="起始点编号" align="center" prop="startNo" />
      <el-table-column label="结束点编号" align="center" prop="endNo" />
      <el-table-column label="焊缝姿态" align="center" prop="weldAttitude" :formatter="weldAttitudeFormatter" />`
      <el-table-column label="焊脚要求" align="center" prop="toeRequirement" />
      <el-table-column label="焊缝长度" align="center" prop="weldLength" />
      <el-table-column label="角度" align="center" prop="angles" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['zndd:action:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['zndd:action:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
      </el-col>
    </el-row>

    <!-- 添加或修改动作信息对话框 -->
<!--    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>-->
      <el-dialog :title="title" style="align-content: center;" :visible.sync="open" width="850px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
<!--        <el-form-item label="部门ID" prop="deptId">-->
<!--          <el-input v-model="form.deptId" placeholder="请输入部门ID" />-->
<!--        </el-form-item>-->
        <el-row>
          <el-col :span="12">
            <el-form-item label="焊缝编号" prop="weldNo">
              <el-input v-model="form.weldNo" placeholder="请输入焊缝编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品类型" prop="productTypeId">
              <el-select v-model="form.productTypeId" placeholder="请选择产品类型">
                <el-option
                  v-for="dict in productLists"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="焊缝区域X" prop="weldZoneX">
              <el-input v-model="form.weldZoneX" placeholder="请输入焊缝区域X" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="焊缝区域Y" prop="weldZoneY">
              <el-input v-model="form.weldZoneY" placeholder="请输入焊缝区域Y" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="起始点编号" prop="startNo">
              <el-input v-model="form.startNo" placeholder="请输入起始点编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束点编号" prop="endNo">
              <el-input v-model="form.endNo" placeholder="请输入结束点编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="焊缝姿态" prop="weldAttitude">
              <el-select v-model="form.weldAttitude" placeholder="请选择焊缝姿态">
                <el-option
                  v-for="parameter in parameterLists"
                  :key="parameter.value"
                  :label="parameter.label"
                  :value="parameter.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="焊脚要求" prop="toeRequirement">
              <el-input v-model="form.toeRequirement" placeholder="请输入焊脚要求" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="焊缝长度" prop="weldLength">
              <el-input v-model="form.weldLength" placeholder="请输入焊缝长度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角度" prop="angles">
              <el-input v-model="form.angles"  placeholder="请输入角度" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 焊缝数据导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的焊缝数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="焊缝预排" :visible.sync="dialogFormVisible" width="500px" append-to-body>
      <el-form :model="formAction">
        <el-row>
          <el-col >
            <el-form-item label="选择三级产线" :label-width="formLabelWidth">
              <el-tree
                ref="tree1"
                v-model="formAction.threeId"
                :data="lineTreeLists"
                :default-expand-all="true"
                :props="defaultProps"
                node-key="id"
                highlight-current
                @node-click="changeProduct"/>
            </el-form-item>
          </el-col>
          <el-col >
            <el-form-item label="产品类型" :label-width="formLabelWidth">
              <el-select v-model="formAction.productTypeId" placeholder="请选择产品类型" clearable>
                <el-option
                  v-for="param in productByThreeId"
                  :key="param.id"
                  :label="param.productTypeName"
                  :value="param.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="actionYuPai">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listAction,
  getAction,
  delAction,
  addAction,
  updateAction,
  getProductByThreeId, addActionPlan
} from '@/api/zndd/action/action'
import { listProducttype } from '@/api/zndd/product/producttype'
import { listParameter } from '@/api/zndd/action/parameter'
import { getToken } from '@/utils/auth'
import { listAllDetails } from '@/api/zndd/line/details'
import { listAllSet } from '@/api/zndd/line/set'

export default {
  name: "Action",
  data() {
    return {
      showIdColumn: false,
      dialogFormVisible: false,
      formLabelWidth: '120px',
      formAction:{},
      productByThreeId:[],
      lineName: null,
      lineTreeLists:[],
      checkDefaultLine:[],
      threeLines:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 动作信息表格数据
      actionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        weldNo: null,
        twoLineId: null,
        threeLineId: null,
        productTypeId: null,
        jobType: null,
        weldZoneX: null,
        weldZoneY: null,
        startNo: null,
        endNo: null,
        weldAttitude: null,
        toeRequirement: null,
        weldLength: null,
        deviceType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        weldNo:[
          { required: true, message: "焊缝编号不能为空", trigger: "blur" }
        ],productTypeId:[
          { required: true, message: "产品类型不能为空", trigger: "change" }
        ],weldZoneX:[
          { required: true, message: "焊缝区域X不能为空", trigger: "blur" }
        ],weldZoneY:[
          { required: true, message: "焊缝区域Y不能为空", trigger: "blur" }
        ],startNo:[
          { required: true, message: "起始点编号不能为空", trigger: "blur" }
        ],endNo:[
          { required: true, message: "结束点编号不能为空", trigger: "blur" }
        ],weldAttitude:[
          { required: true, message: "焊缝姿态不能为空", trigger: "change" }
        ],toeRequirement:[
          { required: true, message: "焊脚要求不能为空", trigger: "blur" }
        ],weldLength:[
          { required: true, message: "焊缝长度不能为空", trigger: "blur" }
        ],angles:[
          { required: true, message: "角度不能为空", trigger: "blur" }
        ]
      },//左侧产品名称查询参数
      productName:null,
      productLists:[],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      productTypeParams: {
        pageNum: 1,
        pageSize: 50,
        deptId: null,
        productTypeName: null
      },
      parameterParams:{
        pageNum: 1,
        pageSize: 50,
        deptId: null
      },
      //当前Id
      currentProId: null,
      checkDefaultPro1: [],//存放默认选中节点的id
      jobTypes:[],
      parameterLists:[],
      // 焊接参数导入参数
      upload: {
      // 是否显示弹出层（用户导入）
      open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
      // 上传的地址
      url: process.env.VUE_APP_BASE_API + "/zndd/action/importData"
    },
    };
  },
  created() {
    //获取字典表中设备状态
    this.getDicts("zndd_job_type").then(response => {
      this.jobTypes = response.data;
    });
    this.getList();
    this.searchProductName();
    this.getParameterLists();
    this.getLineDetalisList();
  },
  // 查询产品名称
  watch: {
    // productName(newVal) {
    //   this.productTypeParams.productTypeName=newVal;
    //   this.searchProductName();
    // }
    processName(val) {
      this.lineParams.sonLineName = val;
      this.getLineList();
    }
  },
  methods: {
    /** 查询动作信息列表 */
    getList() {
      this.loading = true;
      listAction(this.queryParams).then(response => {
        this.actionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        weldNo: null,
        twoLineId: null,
        threeLineId: null,
        productTypeId: null,
        jobType: null,
        weldZoneX: null,
        weldZoneY: null,
        startNo: null,
        endNo: null,
        weldAttitude: null,
        toeRequirement: null,
        weldLength: null,
        deviceType: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加动作信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAction(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改动作信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAction(this.form).then(response => {
              if(response.code==200){
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }else{
                this.$message.error(response.msg);
              }
            });
          } else {
            addAction(this.form).then(response => {
              if(response.code==200){
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }else{
                this.$message.error(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除动作信息id为"' + ids + '"的数据项？').then(function() {
        return delAction(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('zndd/action/export', {
        ...this.queryParams
      }, `动作信息_${new Date().getTime()}.xlsx`)
    }, /** 序号 */
    indexMethod(index) {
      let pageNum = this.queryParams.pageNum - 1;
      if (pageNum !== -1 && pageNum !== 0) {
        return (index + 1) + (pageNum * this.queryParams.pageSize);
      } else {
        return index + 1;
      }
    },//产品查询
    searchProductName(){
      this.productTypeParams.productTypeName=this.productName;
      listProducttype(this.productTypeParams).then(response => {
        var list = [];
        response.rows.forEach(row => {
          list.push({
            label: row.productTypeName,
            value: row.id,
            id: row.id,
          })
        });
        this.productLists=list;
        if(list.length>0){
          // this.queryParams.productTypeId=list[0].value;
          this.currentProId = list[0].value;
        }
        this.checkDefault1=[this.currentProId];
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(this.currentProId);
        })
        this.getList();
      });
    }, productSearchClick(data){
    this.queryParams.productTypeId=data.value;
    this.getList();
  },jobTypeFormatter(row, column){
      var lt = null;
      this.jobTypes.forEach(jobType => {
        if(jobType.dictValue == row.jobType){
          lt = jobType;
        }
      });
      return lt.dictLabel;
    },productFormatter(row,column){
      var lt = null;
      this.productLists.forEach(product => {
        if(product.value == row.productTypeId){
          lt = product;
        }
      });
      return lt.label;
    },weldAttitudeFormatter(row,column){
      var lt = null;
      this.parameterLists.forEach(actionParameter => {
        if(actionParameter.value == row.weldAttitude){
          lt = actionParameter;
        }
      });
      return lt.label;
    },getParameterLists(){
      listParameter(this.parameterParams).then(response => {
        var list = [];
        response.rows.forEach(row => {
          list.push({
            label: row.weldingAttitude,
            value: row.id,
          })
        });
        this.parameterLists = list;
      });
    },/** 导入按钮操作 */
  handleImport() {
    this.upload.title = "焊缝数据导入";
    this.upload.open = true;
  },
  /** 下载模板操作 */
  importTemplate() {
    this.download('zndd/action/importTemplate', {
    }, `动作信息模板_${new Date().getTime()}.xlsx`)
  },
  // 文件上传中处理
  handleFileUploadProgress(event, file, fileList) {
    this.upload.isUploading = true;
  },
  // 文件上传成功处理
  handleFileSuccess(response, file, fileList) {
    this.upload.open = false;
    this.upload.isUploading = false;
    this.$refs.upload.clearFiles();
    this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    this.getList();
  },
  // 提交上传文件
  submitFileForm() {
      this.$refs.upload.submit();
  },lineClick(data){
      this.queryParams.threeLineId=data.id;
      this.getList();
  },//查询二级产线信息
    getLineDetalisList(){
      listAllDetails().then(response => {
        this.detailsList = response.rows;
        this.getLineSetList();
      });
    },//查询三级产线信息
    getLineSetList(){
      listAllSet().then(response => {
        var list = [];
        this.threeLines=response;
        this.detailsList.forEach(details => {
          var sets = [];
          response.rows.forEach(row => {
            if(details.id == row.lineId){
              sets.push({
                label:row.threeLineName,
                value:row.lineNo,
                lineId:row.lineId,
                id:row.id,
              });
            }
          });
          list.push({
            id:details.id,
            label:details.sonLineName,
            value:details.lineNo,
            children:sets
          });
        });
        this.lineTreeLists = list;
        this.queryParams.twoLineId=this.lineTreeLists[0].lineId;
        this.$nextTick(()=>{
          this.$refs.tree.setCurrentKey(this.lineTreeLists[0].children[0].id);
        })
        this.lineClick(this.lineTreeLists[0].children[0].id);
      });
    },openWalkthrough(){
      this.dialogFormVisible = true;
    },changeProduct(data, checked, node){
      this.formAction.threeId=data.id;
      this.formAction.threeNo=data.value;
      getProductByThreeId(data.id).then(response => {
        this.productByThreeId=response;
      })
    },actionYuPai(){
      addActionPlan(this.formAction.threeId,this.formAction.productTypeId,this.formAction.threeNo).then(response => {
        if(response.code==200){
          this.$modal.msgSuccess("预排成功");
          this.dialogFormVisible = false;
          this.getList();
        }else{
          this.$modal.msgError(response.msg);
        }
      })
    },twoLineFormatter(row){
      var lt = null;
      this.detailsList.forEach(two => {
        if(two.id == row.twoLineId){
          lt = two;
        }
      });
      return lt.lineNo;
    },threeLineFormatter(row){
      var lt = null;
      this.threeLines.rows.forEach(three => {
        if(three.id == row.threeLineId){
          lt = three;
        }
      });
      return lt.lineNo;
    }

  }
};
</script>

<style lang="css" scoped>
::v-deep .el-tree-node__content:hover{
  background-color: #409EFF;
  color: #ffffff;
}
::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content{
  background-color: #409EFF;
  color: #ffffff;
}
</style>
